<template>
    <div class="typing-container">
        <!-- 展示内容 -->
        <span v-if="displayText.length > 0">{{ displayText }}</span>
        <!-- 光标 -->
        <span v-show="showCursor" class="typing-cursor"></span>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 配置参数
const config = {
    textToType: "生活就像骑自行车，要想保持平衡就得不断前进。 —— 阿尔伯特·爱因斯坦",
    typingSpeed: 100,
    pauseBeforeComplete: 3000
}


// 当前显示的文本
const displayText = ref('')
// 是否显示光标
const showCursor = ref(true)
// 是否正在打字
const isTyping = ref(false)

let typingTimer = null
let typingDeleteTimer = null


// 打字函数
const typeWriter = () => {
    if (displayText.value.length < config.textToType.length) {
        displayText.value = config.textToType.substring(0, displayText.value.length + 1)
        typingTimer = setTimeout(typeWriter, config.typingSpeed)
    } else {
        // 完成打字后，让光标多闪烁几次再停止
        setTimeout(() => {
            // 从后往前删除文字
            if (displayText.value.length > 0) {
                typingDeleteTimer = setTimeout(deleteTypeWriter, config.typingSpeed)
            } else {
                isTyping.value = false
            }
        }, config.pauseBeforeComplete)
    }
}

// 删除打字函数
const deleteTypeWriter = () => {
    if (displayText.value.length > 0) {
        displayText.value = displayText.value.substring(0, displayText.value.length - 1)
        typingDeleteTimer = setTimeout(deleteTypeWriter, config.typingSpeed)
    } else {
        // 删除所有的文字后，让光标多闪烁几次再停止
        setTimeout(() => {
            isTyping.value = false
        }, config.pauseBeforeComplete)
    }
}

// 开始/重置打字
const startTyping = () => {
    if (!isTyping.value) {
        clearTimeout(typingTimer)
        clearTimeout(typingDeleteTimer)
        isTyping.value = true
        displayText.value = ''
        showCursor.value = true
        typeWriter()
    }
}
onMounted(() => {
    setInterval(() => {
        startTyping()
    }, 5000)
})

// 组件卸载时清理定时器
onUnmounted(() => {
    clearTimeout(typingTimer)
    clearTimeout(typingDeleteTimer)
})
</script>

<style scoped>
.typing-container {
    padding: 30px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 15px;
    display: inline;
    color: #fff;
    font-weight: bold;
    font-size: 25px;
}

.typing-cursor {
    border-right: 2px solid currentColor;
    animation: cursor-blink 1.2s infinite;
    margin-left: 2px;
    font-size: 25px;
}

@keyframes cursor-blink {

    0%,
    100% {
        opacity: 1;
    }

    50% {
        opacity: 0;
    }
}
</style>